package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"os"
	"strconv"
	"strings"
	"time"
)

type UploadController struct {
	beego.Controller
}

func (u *UploadController) Upload() {
	//anchor, _ := u.GetInt("anchor")
	file, h, err := u.GetFile("file")
	if err != nil {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "文件接收失败",
		}
		u.ServeJSON()
		return
	}
	if h.Size >= 1024*1024*30 {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "文件过大",
		}
		u.ServeJSON()
		return
	}
	video := []string{"mp4"}
	sux := strings.Split(h.Filename, ".")
	videoName := sux[1]
	if !strings.Contains(strings.Join(video, ""), videoName) {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "文件格式有误",
		}
		u.ServeJSON()
		return
	}
	fileName := strconv.Itoa(int(time.Now().Unix())) + "." + videoName
	src := "./static/video/" + fileName
	openFille, err := os.OpenFile(src, os.O_CREATE|os.O_WRONLY, 0777)
	if err != nil {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "文件打开失败",
		}
		u.ServeJSON()
		return
	}
	_, err = io.Copy(openFille, file)
	if err != nil {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "文件上传失败",
		}
		u.ServeJSON()
		return
	}
	u.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "文件上传成功",
	}
	u.ServeJSON()
}
